import numpy as np
import cv2 as cv


def resize_image(img: np.ndarray, new_size: tuple, letterbox=True):
    """
    当 letterbox 为 True 时，不失真地修改图片的宽高
    """
    img_height, img_width, _ = img.shape
    target_height, target_width = new_size
    if letterbox:
        scale = min(target_height / img_height, target_width / img_width)
        new_height = int(img_height * scale)
        new_width = int(img_width * scale)
        img = cv.resize(img, (new_width, new_height), interpolation=cv.INTER_LINEAR)
        img_background = np.ones((target_height, target_width, 3), dtype=np.uint8) * 128
        img_background[
            (target_height - new_height) // 2: (target_height - new_height) // 2 + new_height,
            (target_width - new_width) // 2: (target_width - new_width) // 2 + new_width,
            :
        ] = img
        resized_img = img_background
    else:
        resized_img = cv.resize(img, new_size)
    return resized_img
